# 导入库
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, accuracy_score
from joblib import dump
from sklearn.svm import SVC
from sklearn.preprocessing import LabelEncoder



class Classification:
    def __init__(self):
        self.df = pd.read_csv('fina_indicator.csv')
    
    def get_conditions(self):
        """
        分类前准备
        """
        df = self.df
        
        # 计算收益和风险比例
        df['max_ratio'] = df['max_close'] / df['the_close']  # 收益潜力
        df['min_ratio'] = df['min_close'] / df['the_close']  # 风险潜力
        
        # 自动划分高低阈值
        high_return_threshold = df['max_ratio'].quantile(0.4)  # 前40%定义为高收益
        high_risk_threshold = df['min_ratio'].quantile(0.4)    # 前40%定义为高风险
        
        # 生成分类标签
        conditions = [
            (df['max_ratio'] >= high_return_threshold) & (df['min_ratio'] >= high_risk_threshold),
            (df['max_ratio'] < high_return_threshold) & (df['min_ratio'] >= high_risk_threshold),
            (df['max_ratio'] >= high_return_threshold) & (df['min_ratio'] < high_risk_threshold),
            (df['max_ratio'] < high_return_threshold) & (df['min_ratio'] < high_risk_threshold)
        ]
        choices = ['高收益高风险', '低收益高风险', '高收益低风险', '低收益低风险']
        df['category'] = np.select(conditions, choices, default='未知')
        
        # 特征选择
        features = df[['eps','total_revenue_ps','undist_profit_ps','gross_margin','fcff','fcfe','tangible_asset','bps',
                       'grossprofit_margin','npta']]
        
        # 标签编码
        label_encoder = LabelEncoder()
        df['category_encoded'] = label_encoder.fit_transform(df['category'])
        
        # 数据标准化
        scaler = StandardScaler()
        X = scaler.fit_transform(features)
        y = df['category_encoded']
        # 划分训练集和测试集
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
        dump(scaler, 'scaler.joblib')
        return X_train, X_test, y_train, y_test, label_encoder
        
    def knn_utils(self, X_train, X_test, y_train, y_test, label_encoder):
        """
        KNN分类器
        """
        # 初始化KNN分类器
        knn = KNeighborsClassifier(n_neighbors=3)
        # 训练模型
        knn.fit(X_train, y_train)
        # 预测
        y_pred = knn.predict(X_test)
        # 评估模型
        print(classification_report(y_test, y_pred, target_names=label_encoder.classes_))
        dump(knn, 'knn_model.joblib')
        dump(label_encoder, 'label_encoder.joblib')
        def svc_utils(self, X_train, X_test, y_train, y_test, label_encoder):
            """
            SVC分类器
            """
            # 初始化SVC分类器
            svc = SVC(kernel='linear', C=1.0, random_state=42)
            # 训练模型
            svc.fit(X_train, y_train)
            # 预测
            y_pred = svc.predict(X_test)
            # 评估模型
            print(classification_report(y_test, y_pred, target_names=label_encoder.classes_))
            dump(svc, 'svc_model.joblib')
            dump(label_encoder, 'label_encoder.joblib')
            
if __name__ == '__main__':
    # 创建分类实例并获取数据
    classifier = Classification()
    X_train, X_test, y_train, y_test, label_encoder = classifier.get_conditions()
    
    # 训练模型
    model = classifier.svc_utils(X_train, X_test, y_train, y_test, label_encoder)
    print('Finished Training')